// create-order.js
const api = require('../../utils/api.js')
const permissionUtils = require('../../utils/permissions.js')
const pagePermission = require('../../utils/pagepermission.js')

Page({
  data: {
    isEdit: false,
    orderId: null,
    submitting: false,
    formData: {
      customer_name: '',
      customer_phone: '',
      delivery_time: '',
      remark: ''
    },
    modelList: [], // 所有可用的产品型号
    filteredModelList: [], // 过滤后的产品型号列表
    modelItems: [], // 当前订单的产品型号项
    searchKeyword: '', // 搜索关键词
    totalQuantity: 0,
    selectedModelCount: 0
  },

  onLoad(options) {
    // 页面权限检查
    if (!pagePermission.requirePagePermission('pages/create-order/create-order')) {
      return
    }
    
    if (options.id) {
      this.setData({
        isEdit: true,
        orderId: options.id
      })
      this.loadOrderDetail(options.id)
    }
    this.loadModelList()
    // 初始化一个空的型号项
    this.addModelItem()
  },

  // 加载产品型号列表
  loadModelList() {
    api.getModels().then(res => {
      const modelList = res.data.map(item => ({
        ...item,
        display_name: `${item.product.name} - ${item.name}`
      }))
      this.setData({ modelList })
      this.filterModelList() // 加载时也进行一次过滤
    }).catch(err => {
      console.error('加载产品型号失败:', err)
      wx.showToast({
        title: '加载产品型号失败',
        icon: 'error'
      })
    })
  },

  // 加载订单详情（编辑模式）
  loadOrderDetail(orderId) {
    api.getOrderDetail(orderId).then(res => {
      const order = res.data
      this.setData({
        formData: {
          customer_name: order.customer_name || '',
          customer_phone: order.customer_phone || '',
          delivery_time: order.delivery_time ? (typeof order.delivery_time === 'number' ? this.formatTimestamp(order.delivery_time) : order.delivery_time.split(' ')[0]) : '',
          remark: order.remark || ''
        }
      })
      
      // 处理订单型号数据
      if (order.order_models && order.order_models.length > 0) {
        const modelItems = order.order_models.map(orderModel => {
          // 找到对应的型号索引
          const modelIndex = this.data.modelList.findIndex(model => model.id === orderModel.model_id)
          return {
            modelIndex: modelIndex >= 0 ? modelIndex : -1,
            quantity: orderModel.quantity || 0,
            color: orderModel.color || '',
            error: ''
          }
        })
        this.setData({ modelItems })
        this.calculateSummary()
      }
    }).catch(err => {
      console.error('加载订单详情失败:', err)
      wx.showToast({
        title: '加载订单详情失败',
        icon: 'error'
      })
    })
  },

  // 客户名称输入
  onCustomerNameInput(e) {
    this.setData({
      'formData.customer_name': e.detail.value
    })
  },

  // 客户电话输入
  onCustomerPhoneInput(e) {
    this.setData({
      'formData.customer_phone': e.detail.value
    })
  },

  // 交货时间选择
  onDeliveryTimeChange(e) {
    this.setData({
      'formData.delivery_time': e.detail.value
    })
  },


  // 备注输入
  onRemarkInput(e) {
    this.setData({
      'formData.remark': e.detail.value
    })
  },

  // 添加型号项
  addModelItem() {
    const modelItems = this.data.modelItems
    modelItems.push({
      modelIndex: -1,
      quantity: 0,
      color: '',
      error: ''
    })
    this.setData({ modelItems })
  },

  // 删除型号项
  deleteModelItem(e) {
    const index = e.currentTarget.dataset.index
    const modelItems = this.data.modelItems
    modelItems.splice(index, 1)
    this.setData({ modelItems })
    this.calculateSummary()
  },

  // 型号选择
  onModelSelect(e) {
    const index = e.currentTarget.dataset.index
    const modelIndex = e.detail.value
    const modelItems = this.data.modelItems
    modelItems[index].modelIndex = modelIndex
    modelItems[index].error = ''
    this.setData({ modelItems })
    this.calculateSummary()
  },

  // 数量输入
  onQuantityInput(e) {
    const index = e.currentTarget.dataset.index
    const quantity = parseInt(e.detail.value) || 0
    const modelItems = this.data.modelItems
    modelItems[index].quantity = quantity
    modelItems[index].error = ''
    this.setData({ modelItems })
    this.calculateSummary()
  },

  // 颜色输入
  onColorInput(e) {
    const index = e.currentTarget.dataset.index
    const color = e.detail.value
    const modelItems = this.data.modelItems
    modelItems[index].color = color
    this.setData({ modelItems })
  },

  // 计算汇总信息
  calculateSummary() {
    const modelItems = this.data.modelItems
    let totalQuantity = 0
    let selectedModelCount = 0
    
    modelItems.forEach(item => {
      if (item.modelIndex >= 0 && item.quantity > 0) {
        totalQuantity += item.quantity
        selectedModelCount++
      }
    })
    
    this.setData({
      totalQuantity,
      selectedModelCount
    })
  },

  // 验证表单
  validateForm() {
    const { formData, modelItems } = this.data
    
    if (!formData.customer_name.trim()) {
      wx.showToast({
        title: '请输入客户名称',
        icon: 'error'
      })
      return false
    }
    
    
    // 交货时间是可选的，不强制验证
    
    // 验证型号项
    let hasValidItem = false
    const newModelItems = modelItems.map(item => {
      if (item.modelIndex < 0) {
        item.error = '请选择型号'
        return item
      }
      if (item.quantity <= 0) {
        item.error = '请输入数量'
        return item
      }
      hasValidItem = true
      item.error = ''
      return item
    })
    
    this.setData({ modelItems: newModelItems })
    
    if (!hasValidItem) {
      wx.showToast({
        title: '请至少添加一个有效的产品型号',
        icon: 'error'
      })
      return false
    }
    
    return true
  },

  // 提交订单
  submitOrder() {
    if (!this.validateForm()) return
    
    this.setData({ submitting: true })
    
    const { formData, modelItems, modelList, isEdit, orderId } = this.data
    
    // 构建型号数据
    const models = []
    modelItems.forEach(item => {
      if (item.modelIndex >= 0 && item.quantity > 0) {
        // 根据搜索状态选择正确的型号列表
        const currentModelList = this.data.searchKeyword ? this.data.filteredModelList : this.data.modelList
        const modelId = currentModelList[item.modelIndex].id
        models.push({
          model_id: modelId,
          quantity: item.quantity,
          color: item.color || ''
        })
      }
    })
    
    const data = {
      ...formData,
      models: models
    }
    
    // 添加调试信息
    console.log('提交的数据:', data)
    console.log('型号数据:', models)
    console.log('搜索关键词:', this.data.searchKeyword)
    console.log('当前型号列表:', this.data.searchKeyword ? this.data.filteredModelList : this.data.modelList)
    console.log('型号项:', this.data.modelItems)
    
    const apiCall = isEdit ? 
      api.updateOrder(orderId, data) : 
      api.createOrder(data)
    
    apiCall.then(res => {
      wx.showToast({
        title: isEdit ? '更新成功' : '创建成功',
        icon: 'success'
      })
      
      // 返回上一页并刷新
      setTimeout(() => {
        const pages = getCurrentPages()
        const prevPage = pages[pages.length - 2]
        if (prevPage && prevPage.refreshOrders) {
          prevPage.refreshOrders()
        }
        wx.navigateBack()
      }, 1500)
    }).catch(err => {
      console.error('提交订单失败:', err)
      const errorMsg = err.msg || '提交失败'
      wx.showToast({
        title: errorMsg,
        icon: 'none',
        duration: 3000
      })
    }).finally(() => {
      this.setData({ submitting: false })
    })
  },

  // 返回上一页
  goBack() {
    wx.navigateBack()
  },

  // 搜索产品型号
  onSearchInput(e) {
    this.setData({
      searchKeyword: e.detail.value
    })
    this.filterModelList()
  },

  // 过滤产品型号列表
  filterModelList() {
    const keyword = this.data.searchKeyword.toLowerCase()
    const filteredList = this.data.modelList.filter(model => 
      model.display_name.toLowerCase().includes(keyword)
    )
    
    this.setData({
      filteredModelList: filteredList
    })
    
    // 重新映射已选择的型号索引
    this.remapModelIndexes()
  },

  // 重新映射型号索引
  remapModelIndexes() {
    const { modelItems, modelList, filteredModelList, searchKeyword } = this.data
    const newModelItems = modelItems.map(item => {
      if (item.modelIndex >= 0) {
        // 获取当前选择的型号ID（基于当前显示的列表）
        let currentModelId
        if (searchKeyword) {
          // 搜索状态下，从过滤列表中获取
          currentModelId = filteredModelList[item.modelIndex]?.id
        } else {
          // 非搜索状态下，从原始列表中获取
          currentModelId = modelList[item.modelIndex]?.id
        }
        
        if (currentModelId) {
          // 在过滤后的列表中查找对应索引
          const newIndex = filteredModelList.findIndex(model => model.id === currentModelId)
          return {
            ...item,
            modelIndex: newIndex >= 0 ? newIndex : -1
          }
        }
      }
      return item
    })
    
    this.setData({ modelItems: newModelItems })
  },

  // 权限检查方法
  hasPermission(module, action) {
    const app = getApp()
    const adminInfo = app.globalData.adminInfo
    if (!adminInfo) {
      return false
    }
    return permissionUtils.hasPermission(adminInfo.id, module, action);
  },

  // 显示权限拒绝提示
  showPermissionDenied(module, action) {
    wx.showToast({
      title: `您没有${module}模块的${action}权限`,
      icon: 'none'
    })
  },

  // 格式化时间戳为日期字符串
  formatTimestamp(timestamp) {
    if (!timestamp) return '';
    const date = new Date(timestamp * 1000);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
  }
}) 